package com.tanxi521.tnweb.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class FileUploadUtils {

    public static Map<String, Object> uploadHeadImg(MultipartFile headImg, String userName) {
        String path = "D:\\MC服务器\\web\\user\\user_head";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdir = file.mkdir();
        }
        String filename = headImg.getOriginalFilename();
        if (filename != null) {
            String correctSuffix = "png,PNG,jpg,JPG,gif,GIF,webp,WEBP,jpeg,JPEG";
            String substring = filename.substring(filename.lastIndexOf(".") + 1);
            if (!correctSuffix.contains(substring)) {
                return Result.error("头像只能是 png,jpg,gif,webp,jpeg 文件");
            }
            long maxSize = 8*1024*1024;
            if (headImg.getSize() > maxSize) {
                return Result.error("头像大小不允许超过8M");
            }
            filename = userName + new Date().getTime() + "." + substring;
            try {
                headImg.transferTo(new File(path + File.separator + filename));
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("系统繁忙，头像上传失败");
            }
            String imgPath = "/tnweb/image/user_head/"+ filename;
            return Result.success(imgPath);
        }
        return Result.error("未知问题");
    }
}
